import random, time

# 以列表+字典的方式定义账户信息
user_list = [{'username':'woniu', 'password':'12345', 'phone':'13838389438', 'balance':2000, 'history':''},
             {'username':'qiang', 'password':'23456', 'phone':'18812345678', 'balance':3000, 'history':''}]

# 定义一个全局变量，用于保存当前登录用户的在user_list中的下标，默认未登录的情况下为-1
login_index = -1

# 注册
def reg():
    username = input("请输入用户名[注册]：")
    password = input('请输入密码[注册]：')
    phone = input('请输入电话号码[注册]：')

    if check_user(username) >= 0:
        print("你注册的用户名已经存在.")
    else:
        print("恭喜你，用户名可用.")
        user_info = {}
        user_info['username'] = username
        user_info['password'] = password
        user_info['phone'] = phone
        user_info['balance'] = random.randint(1000, 5000)

        user_list.append(user_info)
        print("恭喜你，注册成功.")
        print(user_list)
        start_menu()


# 登录
def login():
    username = input("请输入用户名[登录]：")
    password = input('请输入密码[登录]：')

    index = check_user(username)
    if index >= 0:
        if user_list[index]['password'] == password:
            print("恭喜你，登录成功.")
            global login_index      # 要在函数中修改全局变量，则必须加global进行声明，如果不修改只读取，只可以直接读取
            login_index = index     # 修改全局变量login_index为当前登录用户的下标
            main_menu()
        else:
            print("抱歉，密码输入错误.")
    else:
        print("抱歉，登录用户名不存在.")


# 查询
def query():
    balance = user_list[login_index]['balance']
    phone = user_list[login_index]['phone']
    print("你的余额为：%d 元，电话号码为：%s." % (balance, phone))
    main_menu()


# 存款
def deposite():
    user_info = user_list[login_index]
    money = input("请输入你要存的钱：")
    if check_number(money):
        save_history(login_index, '存款', money)
        check_balance(login_index, int(money))
    else:
        print("请输入正确的金额.")
        deposite()                  # 递归调用重新存钱

# 取款
def withdraw():
    user_info = user_list[login_index]
    money = input("请输入你要取的钱：")
    if check_number(money) and user_info['balance'] >= int(money):
        save_history(login_index, '取款', money)
        check_balance(login_index, int(money) * -1)
    else:
        print("请输入正确的金额.")
        withdraw()


    # 转账
def transer():
    username = input("请输入对方账户：")
    money = input("请输入转账金额：")
    to_index = check_user(username)
    if to_index == -1:
        print("对方账户名不存在，请重新输入.")
        transer()
    else:
        if check_number(money):
            save_history(login_index, '取款', money)
            save_history(to_index, '存款', money)
            check_balance(login_index, int(money) * -1)
            check_balance(to_index, int(money))
        else:
            print("请输入正确的金额.")



# 流水
def history():
    user_info = user_list[login_index]
    history_list = user_info['history'].split('##')
    for history in history_list:
        print(history)



# 账户余额操作
def check_balance(user_index, money):
    user_info = user_list[user_index]
    user_info['balance'] = user_info['balance'] + money
    user_list[login_index] = user_info
    if money < 0:
        print("恭喜，成功取款：%s 元，当前余额为：%d 元." % (-money, user_info['balance']))
    else:
        print("恭喜，成功存款：%s 元，当前余额为：%d 元." % (money, user_info['balance']))
    main_menu()


# 保存历史流水记录
def save_history(user_index, op_type, money):
    user_info = user_list[user_index]
    before_history = user_info['history']
    this_history = user_info['username'] + ' ' + time.strftime('%Y-%m-%d %H:%M:%S') + ' ' + op_type + ' ' + str(money)
    new_history = before_history + '##' + this_history
    user_info['history'] = new_history
    user_list[user_index] = user_info
    print(user_list)


# 检查
def check_user(username):
    for i in range(len(user_list)):
        if user_list[i]['username'] == username:
            return i

    return -1


# 对输入的字符串进行判断，确认其是否可以转换为一个有效的数字
def check_number(string):
    point = 0
    is_valid = True
    for c in string:
        code = ord(c)
        if (code < 48 and code != 46) or code > 57:
            is_valid = False
            break
        elif code == 46: point += 1

    if point > 1: is_valid = False

    return is_valid


# 构建开始菜单
def start_menu():
    tip = '''
***************** 欢迎来到WoniuATM **********************
***************** 请选择操作菜单 ************************
************* 1. 注册   2. 登录   3. 退卡 ***************
    '''
    print(tip)
    option = input("请输入你的操作选项：")
    if option == "1":
        reg()
    elif option == "2":
        login()
    else:
        exit('谢谢，欢迎下次光临.')


# 构建登录后业务菜单
def main_menu():
    tip = '''
*************************** 恭喜登录蜗牛银行 **********************************
*************************** 请选择操作菜单 ************************************
****** 1. 查询   2. 取款   3. 存款   4. 转账   5. 流水  6. 返回  7. 退卡 *******
        '''
    print(tip)
    option = input("请输入你的操作选项：")
    if option == "1":
        query()
    elif option == "2":
        withdraw()
    elif option == "3":
        deposite()
    elif option == "4":
        transer()
    elif option == "5":
        history()
    elif option == "6":
        start_menu()
    elif option == "7":
        exit('谢谢，欢迎下次光临.')



start_menu()